package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import javafx.scene.shape.Circle;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class SmallVideosApiImpl implements SmallVideosApi {

    @Autowired
    private MongoTemplate mongoTemplate;
   //上传视频
    public void save(Video video) {
        mongoTemplate.save(video);
    }

   //  查询推荐
    public List<Video> findByIds(String[] ids, Integer page, Integer pagesize) {
        //redis中支持的最大推荐数
        int totalPage = PageUtil.totalPage(ids.length, pagesize);
        if (page<=totalPage){
            Criteria criteria = Criteria.where("id").in(ids);
            Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
            List<Video> list = mongoTemplate.find(query, Video.class);
            return list;
        }else {
            return findAll(page-totalPage,pagesize);
        }

    }

    //查询全部
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page - 1) * pagesize);


        return mongoTemplate.find(query,Video.class);
    }

    //查询个人视频
    public PageResult findByUserId(Long uid, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(uid);
        //查询总数
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Video.class);
        //分页查询
         query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Video> list = mongoTemplate.find(query, Video.class);

        return new PageResult(page,pagesize,count,list);
    }
}
